﻿using First_WebAPI.Commons;
using First_WebAPI.Entity.Models;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace First_WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController] 
    public class Test1Controller : ControllerBase
    {
        private readonly UserManager<MyUser> userManager;
        private readonly RoleManager<MyRole> roleManager;
        private readonly IMediator mediator;
        private readonly RabbitMQService rabbitMQService;
        public Test1Controller(UserManager<MyUser> userManager, RoleManager<MyRole> roleManager, IMediator mediator, RabbitMQService rabbitMQService)
        {
            this.userManager = userManager;
            this.roleManager = roleManager;
            this.mediator = mediator;
            this.rabbitMQService = rabbitMQService;
        }
        [HttpGet]
        public void OnGet()
        {
            throw new NotImplementedException();
        }
        [HttpGet]
        public async Task OnGet1()
        {
           await rabbitMQService.SendMessageAsync("你好啊，未来！");
            await mediator.Publish(new MediatRTest("你好啊" + DateTime.Now.ToString()));
        }

        [HttpPost]
        public async Task<ActionResult<ResponseResult>> AddRole(string RoleName)
        {
            ResponseResult rp = new ResponseResult();
            if (!await roleManager.RoleExistsAsync(RoleName))
            {
                MyRole role = new MyRole();
                role.Name = RoleName;
                role.NormalizedName = RoleName;
                var result = await roleManager.CreateAsync(role);
                if (result.Succeeded)
                {
                    rp.Message = "添加成功";
                }
                else
                {
                    rp.Message = result.Errors.First().Description;
                }
            }
            else
            {
                rp.Message = "权限已存在";
            }
            return rp;
        }


        [HttpPost]
        public async Task<ActionResult<ResponseResult>> AddUser(MyUser model)
        {
            ResponseResult rp = new ResponseResult();
            if (model == null) { rp.Message = "参数不能为空"; rp.Code = -1; return rp; }
            var user = userManager.FindByNameAsync(model.UserName);
            if (user.Result == null)
            {
                MyUser myUser = model;
                var result = await userManager.CreateAsync(myUser);
                if (result.Succeeded)
                {
                    rp.Message = "添加成功";
                }
                else
                {
                    rp.Message = result.Errors.First().Description;
                    rp.Code = -1;
                }
            }
            else { rp.Message = "用户已存在"; rp.Code = -1; }
            return rp;

        }
    }
}
